<template>
  <div class="edit-album-dialog">
    <el-dialog
      v-model="visible"
      title="编辑相册"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="相册名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入相册名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="相册描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入相册描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="封面照片">
          <div class="cover-photo-selector">
            <div class="current-cover" v-if="currentCover">
              <img
                :src="getThumbnailUrl(currentCover)"
                :alt="currentCover.fileName"
                @error="handleImageError"
              />
              <div class="cover-actions">
                <el-button size="small" @click="changeCover">
                  更换封面
                </el-button>
              </div>
            </div>
            <div v-else class="no-cover">
              <el-icon size="48"><Picture /></el-icon>
              <p>暂无封面照片</p>
              <el-button size="small" @click="changeCover">
                选择封面
              </el-button>
            </div>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            @click="handleSave"
            :loading="saving"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 选择封面照片对话框 -->
    <el-dialog
      v-model="coverSelectorVisible"
      title="选择封面照片"
      width="80%"
      top="5vh"
      append-to-body
    >
      <div class="cover-selector-content">
        <div class="photos-grid" v-loading="loadingPhotos">
          <div
            v-for="photo in albumPhotos"
            :key="photo.id"
            class="photo-item"
            :class="{ selected: selectedCoverId === photo.id }"
            @click="selectCover(photo)"
          >
            <img
              :src="getThumbnailUrl(photo)"
              :alt="photo.fileName"
              @error="handleImageError"
            />
            <div class="photo-overlay" v-if="selectedCoverId === photo.id">
              <el-icon class="check-icon"><Check /></el-icon>
            </div>
          </div>
        </div>
        
        <div class="pagination-container" v-if="hasMorePhotos">
          <el-button @click="loadMorePhotos" :loading="loadingMore">
            加载更多
          </el-button>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="coverSelectorVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="confirmCoverSelection"
            :disabled="!selectedCoverId"
          >
            确认选择
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Picture, Check } from '@element-plus/icons-vue';
import type { Album, Photo } from '@/types';
import AlbumService from '@/services/albumService';
import PhotoService from '@/services/photoService';

// 定义Props
const props = defineProps<{
  visible: boolean;
  album: Album | null;
}>();

// 定义Emits
const emit = defineEmits<{
  'update:visible': [value: boolean];
  'updated': [album: Album];
}>();

// 组件状态
const formRef = ref<FormInstance>();
const saving = ref(false);
const form = ref({
  name: '',
  description: ''
});

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入相册名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
};

// 封面照片选择相关
const coverSelectorVisible = ref(false);
const loadingPhotos = ref(false);
const loadingMore = ref(false);
const albumPhotos = ref<Photo[]>([]);
const hasMorePhotos = ref(false);
const photosPage = ref(1);
const selectedCoverId = ref<number | null>(null);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

const currentCover = computed(() => {
  if (!props.album) return null;
  
  // 如果有选中的封面照片ID，使用它
  if (selectedCoverId.value) {
    return albumPhotos.value.find(p => p.id === selectedCoverId.value);
  }
  
  // 否则使用相册当前的封面照片
  if (props.album.coverPhotoId) {
    return albumPhotos.value.find(p => p.id === props.album!.coverPhotoId);
  }
  
  // 否则使用第一张照片
  if (albumPhotos.value.length > 0) {
    return albumPhotos.value[0];
  }
  
  return null;
});

// 加载相册照片
const loadAlbumPhotos = async () => {
  if (!props.album) return;
  
  loadingPhotos.value = true;
  photosPage.value = 1;
  
  try {
    const result = await AlbumService.getAlbumPhotos(props.album.id, {
      page: photosPage.value,
      pageSize: 50
    });
    
    albumPhotos.value = result.photos;
    hasMorePhotos.value = result.photos.length === 50;
  } catch (error) {
    console.error('加载相册照片失败:', error);
    ElMessage.error('加载相册照片失败');
  } finally {
    loadingPhotos.value = false;
  }
};

// 加载更多照片
const loadMorePhotos = async () => {
  if (!props.album || !hasMorePhotos.value) return;
  
  loadingMore.value = true;
  photosPage.value += 1;
  
  try {
    const result = await AlbumService.getAlbumPhotos(props.album.id, {
      page: photosPage.value,
      pageSize: 50
    });
    
    albumPhotos.value = [...albumPhotos.value, ...result.photos];
    hasMorePhotos.value = result.photos.length === 50;
  } catch (error) {
    console.error('加载更多照片失败:', error);
    ElMessage.error('加载更多照片失败');
  } finally {
    loadingMore.value = false;
  }
};

// 更换封面
const changeCover = () => {
  coverSelectorVisible.value = true;
  if (albumPhotos.value.length === 0) {
    loadAlbumPhotos();
  }
};

// 选择封面
const selectCover = (photo: Photo) => {
  selectedCoverId.value = photo.id;
};

// 确认封面选择
const confirmCoverSelection = () => {
  coverSelectorVisible.value = false;
};

// 保存相册
const handleSave = async () => {
  if (!formRef.value || !props.album) return;
  
  try {
    await formRef.value.validate();
    
    saving.value = true;
    
    const updates: Partial<Album> = {
      name: form.value.name,
      description: form.value.description
    };
    
    // 如果选择了新的封面照片，更新封面
    if (selectedCoverId.value && selectedCoverId.value !== props.album.coverPhotoId) {
      updates.coverPhotoId = selectedCoverId.value;
    }
    
    const updatedAlbum = await AlbumService.updateAlbum(props.album.id, updates);
    
    ElMessage.success('相册已更新');
    emit('updated', updatedAlbum);
    handleClose();
  } catch (error) {
    console.error('更新相册失败:', error);
    ElMessage.error('更新相册失败');
  } finally {
    saving.value = false;
  }
};

// 关闭对话框
const handleClose = () => {
  visible.value = false;
  selectedCoverId.value = null;
  
  // 重置表单
  if (props.album) {
    form.value = {
      name: props.album.name,
      description: props.album.description || ''
    };
  }
};

// 获取缩略图URL
const getThumbnailUrl = (photo: Photo) => {
  if (photo.thumbnailPath) {
    return `file://${photo.thumbnailPath}`;
  }
  return `file://${photo.filePath}`;
};

// 处理图片加载错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  // 设置默认图片或错误处理
  img.src = '/path/to/default/image.jpg';
};

// 监听对话框可见性变化
watch(visible, (newValue) => {
  if (newValue && props.album) {
    // 初始化表单
    form.value = {
      name: props.album.name,
      description: props.album.description || ''
    };
    
    // 重置封面选择
    selectedCoverId.value = null;
  }
});

// 生命周期
onMounted(() => {
  if (props.visible && props.album) {
    form.value = {
      name: props.album.name,
      description: props.album.description || ''
    };
  }
});
</script>

<style scoped lang="scss">
.edit-album-dialog {
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  .cover-photo-selector {
    .current-cover {
      position: relative;
      width: 200px;
      height: 150px;
      border-radius: 8px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .cover-actions {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        padding: 8px;
        background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
        display: flex;
        justify-content: center;
        
        .el-button {
          padding: 4px 8px;
          font-size: 12px;
        }
      }
    }
    
    .no-cover {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 200px;
      height: 150px;
      border: 1px dashed var(--el-border-color);
      border-radius: 8px;
      color: var(--el-text-color-secondary);
      
      p {
        margin: 8px 0;
        font-size: 14px;
      }
    }
  }
}

.cover-selector-content {
  .photos-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 16px;
    max-height: 60vh;
    overflow-y: auto;
    padding: 8px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    
    .photo-item {
      position: relative;
      aspect-ratio: 1;
      border-radius: 8px;
      overflow: hidden;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
      border: 2px solid transparent;
      
      &:hover {
        transform: scale(1.03);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      &.selected {
        border-color: var(--el-color-primary);
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      .photo-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(var(--el-color-primary-rgb), 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        
        .check-icon {
          color: white;
          font-size: 24px;
        }
      }
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 16px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .edit-album-dialog {
    .cover-photo-selector {
      .current-cover,
      .no-cover {
        width: 100%;
        height: 120px;
      }
    }
  }
  
  .cover-selector-content {
    .photos-grid {
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
      gap: 8px;
    }
  }
}
</style>